<template>
  <div class="notification" @click="showMsg">
    <el-badge :is-dot="msgCount > 0" :max="99" :show-zero="false" class="item" :offset="[3, -3]">
      <el-icon size="15">
        <Bell />
      </el-icon>
    </el-badge>
  </div>
  <vol-box v-model="model" :width="420" :padding="5">
    <div style="height:445px">

      <el-tabs v-model="activeName" class="msg-tabs" @tab-click="handleClick">
        <el-tab-pane name="msg">
          <template #label>
            <span class="custom-tabs-label">
              <el-badge :value="msgCount" :show-zero="false" :offset="[-2, 4]"
                badge-style="background-color: #ff1b0b;width: 18px; ">
                消息通知<el-icon size="15"> </el-icon>
              </el-badge>
            </span>
          </template>
          <div class="toolbar">
            <el-button size="small" text type="primary" @click="markAll">全部已读</el-button>
            <el-button size="small" text type="danger" @click="clearList">清空</el-button>
          </div>
          <el-scrollbar :height="400">
            <div class="msg-item" v-for="(item, index) in msg" :key="index">
              <div @click="openItem(item)">
                <div class="title">
                  {{ item.title }}
                </div>
                <div class="desc">{{ item.desc }}</div>
                <div class="bottom">
                  <div class="tag">
                    <el-tag :type="item.tag" size="small">{{ item.type }}</el-tag>
                  </div>
                  <div class="date">{{ item.date }}</div>
                </div>
              </div>
              <!-- 发货消息添加查看按钮 -->
              <div v-if="item.type === '发货'" class="action-buttons">
                <el-button size="small" type="primary" @click.stop="viewShipmentDetail(item)">查看</el-button>
              </div>
              <!-- 审批通过消息添加查看按钮：弹出审批详情，右下角提供出库 -->
              <div v-if="item.type === '审批'" class="action-buttons">
                <el-button size="small" type="success" @click.stop="viewApprovalDetail(item)">查看</el-button>
              </div>
              <!-- 退货消息添加查看按钮 -->
              <div v-if="item.type === '退货'" class="action-buttons">
                <el-button size="small" type="warning" @click.stop="viewReturnDetail(item)">查看</el-button>
              </div>
            </div>
          </el-scrollbar>
        </el-tab-pane>
        <el-tab-pane label="已读消息" name="read">
          <el-scrollbar :height="400">
            <div v-if="readMsg.length === 0">
              <vol-empty></vol-empty>
            </div>
            <div v-else class="msg-item" v-for="(item, index) in readMsg" :key="index">
              <div @click="openItem(item)">
                <div class="title" style="color: #999;">
                  {{ item.title }}
                </div>
                <div class="desc" style="color: #aaa;">{{ item.desc }}</div>
                <div class="bottom">
                  <div class="tag">
                    <el-tag :type="item.tag" size="small">{{ item.type }}</el-tag>
                  </div>
                  <div class="date">{{ item.date }}</div>
                </div>
              </div>
              <!-- 发货消息添加查看按钮（已读消息禁用） -->
              <div v-if="item.type === '发货'" class="action-buttons">
                <el-button size="small" type="info" disabled>已读</el-button>
              </div>
            </div>
          </el-scrollbar>
        </el-tab-pane>
      </el-tabs>
    </div>

  </vol-box>
  
  <!-- 发货详情弹窗 -->
  <el-dialog 
    v-model="shipmentDetailVisible" 
    title="发货详情" 
    width="600px"
    :close-on-click-modal="false">
    <el-form :model="shipmentDetail" label-width="120px">
      <el-form-item label="发货单号">
        <el-input v-model="shipmentDetail.shipment_no" readonly></el-input>
      </el-form-item>
      <el-form-item label="订单编号">
        <el-input v-model="shipmentDetail.order_no" readonly></el-input>
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input v-model="shipmentDetail.product_name" readonly></el-input>
      </el-form-item>
      <el-form-item label="数量">
        <el-input v-model="shipmentDetail.Num" readonly></el-input>
      </el-form-item>
      <el-form-item label="单价">
        <el-input v-model="shipmentDetail.unit_price" readonly></el-input>
      </el-form-item>
      <el-form-item label="总金额">
        <el-input v-model="shipmentDetail.total_amount" readonly></el-input>
      </el-form-item>
      <el-form-item label="发货地址">
        <el-input v-model="shipmentDetail.Address" type="textarea" :rows="2" readonly></el-input>
      </el-form-item>
      <el-form-item label="货运公司">
        <el-input v-model="shipmentDetail.company_name" readonly></el-input>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-input v-model="shipmentDetail.CreateDate" readonly></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="shipmentDetailVisible = false">关闭</el-button>
      <el-button type="primary" @click="goToShipment">发货</el-button>
    </template>
  </el-dialog>

  <!-- 审批详情弹窗 -->
  <el-dialog 
    v-model="approvalDetailVisible" 
    title="审批详情" 
    width="560px"
    :close-on-click-modal="false">
    <el-form :model="approvalDetail" label-width="120px">
      <el-form-item label="任务编号">
        <el-input v-model="approvalDetail.TaskNo" readonly></el-input>
      </el-form-item>
      <el-form-item label="任务名称">
        <el-input v-model="approvalDetail.TaskName" readonly></el-input>
      </el-form-item>
      <el-form-item label="发起人">
        <el-input v-model="approvalDetail.Sponsor" readonly></el-input>
      </el-form-item>
      <el-form-item label="发起时间">
        <el-input v-model="approvalDetail.StartTime" readonly></el-input>
      </el-form-item>
      <el-form-item label="待办类型">
        <el-input :value="approvalDetail.To_doList === 2 ? '已处理' : '未处理'" readonly></el-input>
      </el-form-item>
      <el-form-item label="处理状态">
        <el-input :value="approvalDetail.ProcessingStatus === 2 ? '已处理(同意)' : '待审核'" readonly></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="approvalDetailVisible = false">关闭</el-button>
      <el-button type="primary" @click="goToOutboundFromApproval">出库</el-button>
    </template>
  </el-dialog>

  <!-- 退货详情弹窗 -->
  <el-dialog 
    v-model="returnDetailVisible" 
    title="退货详情" 
    width="600px"
    :close-on-click-modal="false">
    <el-form :model="returnDetail" label-width="120px">
      <el-form-item label="退货编号">
        <el-input v-model="returnDetail.return_no" readonly></el-input>
      </el-form-item>
      <el-form-item label="订单编号">
        <el-input v-model="returnDetail.order_no" readonly></el-input>
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input v-model="returnDetail.product_name" readonly></el-input>
      </el-form-item>
      <el-form-item label="数量">
        <el-input v-model="returnDetail.Num" readonly></el-input>
      </el-form-item>
      <el-form-item label="订单金额">
        <el-input v-model="returnDetail.order_amount" readonly>
          <template #prefix>¥</template>
        </el-input>
      </el-form-item>
      <el-form-item label="客户ID">
        <el-input v-model="returnDetail.customer_id" readonly></el-input>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-input v-model="returnDetail.create_time" readonly></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-tag type="success">{{ returnDetail.State }}</el-tag>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="returnDetailVisible = false">关闭</el-button>
      <el-button type="primary" @click="goToReturnOrderPage">查看退货记录</el-button>
    </template>
  </el-dialog>

  <!-- <el-dropdown trigger="hover">
    <div class="notification">
      <el-badge
       :is-dot="msgCount>0"
        :max="99"
        :show-zero="false"
        class="item"
        :offset="[3, -3]"
      >
        <el-icon size="15">
          <Bell />
        </el-icon>
      </el-badge>
    </div>
    <template #dropdown>
      <el-tabs v-model="activeName" class="msg-tabs" @tab-click="handleClick">
        <el-tab-pane name="msg">
          <template #label>
            <span class="custom-tabs-label">
              <el-badge
                :value="msgCount"
                :show-zero="false"
                :offset="[-2, 4]"
                badge-style="background-color: #ff1b0b;width: 18px; "
              >
                消息通知<el-icon size="15"> </el-icon>
              </el-badge>
            </span>
          </template>
          <el-scrollbar :max-height="400">
            <div class="msg-item" v-for="(item, index) in msg" :key="index">
              <div class="title">
                {{ item.title }}
              </div>
              <div class="desc">{{ item.desc }}</div>
              <div class="bottom">
                <div class="tag">
                  <el-tag :type="item.tag" size="small">{{ item.type }}</el-tag>
                </div>
                <div class="tag">生产部</div>
                <div class="date">{{ item.date }}</div>
              </div>
            </div>
          </el-scrollbar>
        </el-tab-pane>
        <el-tab-pane label="已读消息" name="read"> <vol-empty></vol-empty></el-tab-pane>
      </el-tabs>
    </template>
  </el-dropdown> -->
</template>

<script setup>
import VolEmpty from "@/components/basic/VolEmpty.vue";
import { reactive, ref, getCurrentInstance, onMounted, computed } from "vue";
import { messages, msgCount as globalMsgCount, markAllRead as busMarkAllRead, clearAll as busClearAll } from "./messageBus.js";

const props = defineProps({
  list: {
    type: Array,
    default: () => {
      return [];
    },
  },
});

const model = ref(false);
const activeName = ref("msg");
const { proxy } = getCurrentInstance();

// 本地消息列表（从数据库加载）
const allMessages = ref([]);
const readMessages = ref([]);

// 发货详情弹窗
const shipmentDetailVisible = ref(false);
const shipmentDetail = ref({
  shipment_no: '',
  order_no: '',
  product_name: '',
  Num: '',
  unit_price: '',
  total_amount: '',
  Address: '',
  company_name: '',
  CreateDate: ''
});

// 审批详情
const approvalDetailVisible = ref(false);
const approvalDetail = ref({
  TaskId: 0,
  TaskNo: '',
  TaskName: '',
  Sponsor: '',
  StartTime: '',
  To_doList: 0,
  ProcessingStatus: 0
});
// 当前查看的审批消息(用于点击出库后再标记已读)
const approvalViewingMessage = ref(null);

// 退货详情
const returnDetailVisible = ref(false);
const returnDetail = ref({
  return_no: '',
  order_no: '',
  product_name: '',
  customer_id: '',
  create_time: '',
  order_amount: 0,
  Num: 0,
  State: ''
});
// 当前查看的退货消息(用于标记已读)
const returnViewingMessage = ref(null);

// 当前查看的消息（用于在点击发货按钮后标记为已读）
const currentViewingMessage = ref(null);

// 计算未读消息
const msg = computed(() => {
  return allMessages.value.filter(m => m.IsRead === 0);
});

// 计算已读消息
const readMsg = computed(() => {
  return allMessages.value.filter(m => m.IsRead === 1);
});

// 未读消息数量
const msgCount = computed(() => {
  return msg.value.length;
});

// 从数据库加载消息列表
const loadMessages = async () => {
  try {
    const res = await proxy.http.get('/api/Sys_Notification/getList', { pageIndex: 1, pageSize: 100 });
    console.log('加载消息列表:', res);
    if (res && res.status && res.data) {
      allMessages.value = res.data.map(item => ({
        id: item.notification_id,
        title: item.notification_title,
        desc: item.notification_description,
        type: item.notification_messagetype,
        tag: item.notification_tag,
        date: item.notification_createdate ? new Date(item.notification_createdate).toLocaleString() : '',
        IsRead: item.notification_isread,
        route: {
          path: item.notification_routepath,
          query: item.notification_routequery ? JSON.parse(item.notification_routequery) : {}
        }
      }));
      console.log('消息列表已加载，共', allMessages.value.length, '条');
    }
  } catch (error) {
    console.error('加载消息列表失败:', error);
  }
};

// 标记单条消息为已读
const markAsRead = async (id) => {
  try {
    const res = await proxy.http.post('/api/Sys_Notification/markAsRead', { id });
    if (res && res.status) {
      console.log('消息已标记为已读:', id);
      // 更新本地状态
      const message = allMessages.value.find(m => m.id === id);
      if (message) {
        message.IsRead = 1;
      }
    }
  } catch (error) {
    console.error('标记消息失败:', error);
  }
};

// 打开消息项
const openItem = async (item) => {
  // 标记为已读
  if (item.IsRead === 0) {
    await markAsRead(item.id);
  }
  
  // 若包含跳转路由，打开相应页面
  if (item.route && item.route.path) {
    proxy.$tabs.open({ 
      name: item.type === '订单' ? '订单表' : '发货表', 
      path: item.route.path, 
      query: item.route.query || {} 
    }, false);
  }
};

// 显示消息面板
const showMsg = () => {
  model.value = true;
  loadMessages(); // 每次打开时重新加载
};

// 全部已读
const markAll = async () => {
  try {
    const res = await proxy.http.post('/api/Sys_Notification/markAllAsRead');
    if (res && res.status) {
      proxy.$message.success('已全部标记为已读');
      await loadMessages(); // 重新加载
    }
  } catch (error) {
    console.error('全部已读失败:', error);
    proxy.$message.error('操作失败');
  }
};

// 清空消息
const clearList = async () => {
  try {
    const res = await proxy.http.post('/api/Sys_Notification/clearAll');
    if (res && res.status) {
      proxy.$message.success('已清空所有消息');
      allMessages.value = [];
    }
  } catch (error) {
    console.error('清空消息失败:', error);
    proxy.$message.error('操作失败');
  }
};

// 切换标签页
const handleClick = (tab) => {
  console.log('切换到标签页:', tab.props.name);
};

// 查看发货详情
const viewShipmentDetail = async (item) => {
  try {
    console.log('=== 查看发货详情 ===');
    console.log('消息对象:', item);
    console.log('消息路由:', item.route);
    console.log('路由查询参数:', item.route?.query);
    
    // 从消息的 route.query 中获取发货单号
    const shipment_no = item.route?.query?.shipment_no;
    
    console.log('提取的发货单号:', shipment_no);
    console.log('发货单号类型:', typeof shipment_no);
    
    if (!shipment_no) {
      proxy.$message.error('无法获取发货单号');
      return;
    }
    
    // 调用后端接口获取发货详情
    const requestData = {
      page: 1,
      rows: 1,
      wheres: [{ name: 'shipment_no', value: shipment_no }]
    };
    
    console.log('请求参数:', JSON.stringify(requestData, null, 2));
    
    const res = await proxy.http.post('/api/shipment/getPageData', requestData);
    
    console.log('=== 后端响应 ===');
    console.log('完整响应:', res);
    console.log('响应状态:', res?.status);
    console.log('响应数据:', res?.rows);
    console.log('数据长度:', res?.rows?.length);
    
    // 兼容 status 为数字 0 或布尔值 true 的情况
    const isSuccess = res && (res.status === true || res.status === 0) && res.rows && res.rows.length > 0;
    
    if (isSuccess) {
      const data = res.rows[0];
      console.log('✅ 找到发货记录:', data);
      console.log('所有字段:', Object.keys(data));
      
      // 发货表没有CreateDate字段，使用消息通知的创建时间
      // item.date 已经在 loadMessages 中被格式化为本地时间字符串
      const createDate = item.date;
      
      console.log('消息创建时间:', createDate);
      
      // 从消息通知的描述中提取货运公司名称
      // 描述格式: "发货编号：xxx | 地址：xxx | 货运公司：xxx"
      let company_name = '未知公司';
      if (item.desc) {
        try {
          console.log('消息描述:', item.desc);
          
          // 使用正则表达式提取货运公司名称
          const companyMatch = item.desc.match(/货运公司[：:]\s*([^|]+)/);
          if (companyMatch && companyMatch[1]) {
            company_name = companyMatch[1].trim();
            console.log('✅ 从消息描述提取货运公司名称:', company_name);
          } else {
            console.log('⚠️ 未能从消息描述中提取货运公司名称');
            company_name = `货运公司${data.company_id || '未知'}`;
          }
        } catch (err) {
          console.error('⚠️ 提取货运公司名称失败:', err);
          company_name = `货运公司${data.company_id || '未知'}`;
        }
      }
      
      // 严格按照发货表字段映射
      shipmentDetail.value = {
        shipment_no: data.shipment_no || '',           // 发货编号
        order_no: data.order_no || '',                 // 订单编号
        product_name: data.product_name || '',         // 商品名称
        Num: data.Num || 0,                            // 下单数量
        unit_price: data.unit_price || 0,              // 单价
        total_amount: data.total_amount || 0,          // 总金额
        Address: data.Address || '',                   // 地址
        company_name: company_name,                    // 货运公司（真实名称）
        CreateDate: createDate || '暂无'               // 使用消息的创建时间（已格式化）
      };
      
      // 保存当前查看的消息（用于点击发货按钮后标记为已读）
      currentViewingMessage.value = item;
      
      // 显示弹窗
      shipmentDetailVisible.value = true;
      
      // ✅ 移除这里的标记已读逻辑，改为在点击发货按钮后再标记
      // if (item.IsRead === 0) {
      //   await markAsRead(item.id);
      // }
    } else {
      console.error('❌ 未找到发货记录');
      console.error('响应状态:', res?.status);
      console.error('响应行数:', res?.rows?.length);
      console.error('完整响应:', JSON.stringify(res, null, 2));
      proxy.$message.error('未找到发货记录，请查看控制台日志');
    }
  } catch (error) {
    console.error('❌ 获取发货详情失败:', error);
    console.error('错误详情:', error.message);
    console.error('错误堆栈:', error.stack);
    proxy.$message.error('获取发货详情失败: ' + error.message);
  }
};

// 查看审批消息详情（动态加载任务数据）
const viewApprovalDetail = async (item) => {
  try {
    // 从路由查询中尽量拿 TaskNo
    const taskNo = item.route?.query?.task_no || '';
    // 查询任务数据（根据任务编号或直接取最近已处理）
    let request = { page: 1, rows: 1, wheres: [] };
    if (taskNo) {
      request.wheres.push({ name: 'TaskNo', value: taskNo });
    } else {
      request.wheres.push({ name: 'To_doList', value: 2 });
    }

    const res = await proxy.http.post('/api/taskmanagement/getPageData', request);
    if (res && (res.status === true || res.status === 0) && res.rows && res.rows.length > 0) {
      const row = res.rows[0];
      approvalDetail.value = {
        TaskId: row.TaskId,
        TaskNo: row.TaskNo,
        TaskName: row.TaskName,
        Sponsor: row.Sponsor,
        StartTime: row.StartTime,
        To_doList: row.To_doList,
        ProcessingStatus: row.ProcessingStatus
      };
      approvalDetailVisible.value = true;
      // 暂不标记已读：用户点击“出库”后再标记
      approvalViewingMessage.value = item;
    } else {
      proxy.$message.error('未找到审批记录');
    }
  } catch (err) {
    console.error('加载审批详情失败', err);
    proxy.$message.error('加载审批详情失败');
  }
};

// 在审批详情弹窗点击出库
const goToOutboundFromApproval = async () => {
  try {
    console.log('📦 开始处理出库...');
    console.log('任务编号(发货编号):', approvalDetail.value.TaskNo);
    
    // 调用后端API处理出库：扣减实时库存 + 更新订单状态为已完成
    const res = await proxy.http.post('/api/shipment/processOutbound', {
      shipmentNo: approvalDetail.value.TaskNo  // 任务编号就是发货编号
    });
    
    console.log('出库响应:', res);
    
    if (res && res.status) {
      proxy.$message.success(res.message || '出库成功！');
      console.log('✅ 出库成功');
      
      // 出库成功后将该审批消息标记为已读
      if (approvalViewingMessage.value && approvalViewingMessage.value.IsRead === 0) {
        await markAsRead(approvalViewingMessage.value.id);
      }
      
      // 关闭弹窗
      approvalDetailVisible.value = false;
      model.value = false;
      approvalViewingMessage.value = null;
      
      // 刷新页面数据（如果在发货页面）
      proxy.$tabs.open({ name: '发货表', path: '/shipment' }, false);
    } else {
      proxy.$message.error(res?.message || '出库失败');
      console.error('❌ 出库失败:', res);
    }
  } catch (error) {
    console.error('❌ 出库异常:', error);
    proxy.$message.error('出库失败: ' + (error.message || '未知错误'));
  }
};

// 跳转到发货页面
const goToShipment = async () => {
  try {
    console.log('📋 创建发货任务...');
    console.log('发货单号:', shipmentDetail.value.shipment_no);
    console.log('订单编号:', shipmentDetail.value.order_no);
    
    // 调用后端API创建发货任务并更新订单状态
    const res = await proxy.http.post('/api/shipment/createShipmentTask', {
      shipmentNo: shipmentDetail.value.shipment_no,
      orderNo: shipmentDetail.value.order_no
    });
    
    console.log('后端响应:', res);
    
    if (res && res.status) {
      proxy.$message.success(res.message || '发货任务创建成功，订单状态已更新为已发货');
      console.log('✅ 发货任务创建成功');
      
      // ✅ 在发货成功后，标记消息为已读
      if (currentViewingMessage.value && currentViewingMessage.value.IsRead === 0) {
        await markAsRead(currentViewingMessage.value.id);
        console.log('✅ 消息已标记为已读');
      }
      
      // 关闭详情弹窗
      shipmentDetailVisible.value = false;
      
      // 关闭消息面板
      model.value = false;
      
      // 清空当前查看的消息
      currentViewingMessage.value = null;
      
      // 跳转到发货表页面，并传递订单编号
      proxy.$tabs.open({ 
        name: '发货表', 
        path: '/shipment', 
        query: { 
          order_no: shipmentDetail.value.order_no,
          shipment_no: shipmentDetail.value.shipment_no
        } 
      }, false);
    } else {
      proxy.$message.error(res?.message || '创建发货任务失败');
      console.error('❌ 创建发货任务失败:', res);
    }
  } catch (error) {
    console.error('❌ 创建发货任务异常:', error);
    proxy.$message.error('创建发货任务失败: ' + (error.message || '未知错误'));
  }
};

// 组件挂载时加载消息
onMounted(() => {
  loadMessages();
  // 每30秒自动刷新一次
  setInterval(loadMessages, 30000);
});
</script>
<style scoped lang="less">
.notification {
  outline: none;
  color: #000;
}

// .msg-tabs {
//   width: 260px;
// }
.msg-item {
  border-bottom: 1px solid #eee;
  padding: 10px;

  .title {
    font-weight: bolder;
    font-size: 13px;
    color: #000;
  }

  .desc {
    margin-top: 5px;
    line-height: 1.3;
    font-size: 12px;
    color: #676565;
  }

  .bottom {
    display: flex;
    margin-top: 5px;
    font-size: 12px;
    color: #676565;
  }

  .tag {
    flex: 1;
  }
}

.msg-item:hover {
  cursor: pointer;
  background: #f9f9f9;
}

.action-buttons {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px dashed #eee;
  text-align: right;
}

::v-deep(.el-tabs__header) {
  margin: 0;
}

::v-deep(.el-tabs__content) {
  min-height: 200px;
}

::v-deep(.el-tabs__nav) {
  width: 100%;
  padding: 0 10px;
}

::v-deep(.el-tabs__item) {
  padding: 0 6px;
  flex: 1;
}
</style>
